package com.wds.runner;

import com.wds.common.utils.RedisCacheUtils;
import com.wds.domain.entity.Article;
import com.wds.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-12-03 11:16
 * <p>
 * 实现CommandLineRunner Spring启动完成后会自动执行run方法
 */
@Component
@Slf4j
public class ViewCountRunner implements CommandLineRunner {
    @Autowired
    private RedisCacheUtils redisCache;
    @Autowired
    private ArticleService articleService;

    @Override
    /*
     * 启动时存储浏览量到 redis
     *  viewCountMap : Map<id,count>
     */
    public void run(String... args) throws Exception {
        List<Article> articleList = articleService.list();
        HashMap<Long , Long> viewCounts = new HashMap<>();
        articleList.forEach(item -> {
            viewCounts.put(item.getId(), item.getViewCount());
        });
        redisCache.setCacheMap("viewCountMap", viewCounts);

        log.info("浏览量缓存完成,计数:{}", articleList.size());
    }
}
